package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.Result;
import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private HttpServletRequest req;

    @Override
    public Result findUser(String username, String password) {

        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);

        User selectOne = loginMapper.selectOne(wrapper);

        if (selectOne == null) {
            return new Result(false, "用户不存在");
        }

        if (!selectOne.getPassword().equals(pwd)) {
            return new Result(false, "密码有误");
        }
        HttpSession session = req.getSession();
        session.setAttribute("username", selectOne.getUsername());
        return new Result(true, "登录成功", selectOne);
    }

}
